package de.gwtprime.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;

import org.apache.log4j.Logger;

import de.gwtprime.server.model.Order;
import de.gwtprime.shared.Day;
import de.gwtprime.shared.Stock;


public class BTCchartLoader {

	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(BTCchartLoader.class);
	
	public static void main(String[] args) throws IOException {
		
		loadBTCDataNew();
	}

	public static Stock loadBTCData() throws IOException {
		Stock stock = new Stock();
		
		List<Day> days = new ArrayList<Day>();
		
		String url = "http://api.bitcoincharts.com/v1/trades.csv?symbol=mtgoxUSD";
		
		// Create the url from the string
		URL yahooUrl = null;
		try {
			yahooUrl = new URL(url);
		} catch (MalformedURLException e) {
			logger.error("Url to call yahoo webservice is not correct", e);
		}
		
		// Check the url-connection
		HttpURLConnection urlConnection = (HttpURLConnection) yahooUrl.openConnection();
		if(urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
			logger.error("No connection possible to: "+yahooUrl+", Status: "+urlConnection.getResponseCode());
			//logger.error("No connection possible to: "+yahooUrl+", Status: "+urlConnection.getResponseCode());
			return null;
		}
		
		fillStackWithYahooData(yahooUrl);
		
		int size = stack.size();
		
		
		Date lastDate = null;
		
		List<Double> priceForThisInterval = new ArrayList<Double>();
		
		boolean first = true;
		for(int j=0;j<size;j++){

			String inputLine2 = stack.pop();
			
			String[] s = inputLine2.split(",");
			
			// adding 000 is needed to parse unixtime
			Date d = new Date(Long.parseLong(s[0])*1000);
			
			if(first){
				lastDate= d;
				first = false;
			}
			
			Double price = Double.parseDouble(s[1]);
			if(d.getTime() <= lastDate.getTime()+200000){
				priceForThisInterval.add(price);
			}else{
				
				days.add(new Day(lastDate, getAverage(priceForThisInterval)));
				priceForThisInterval = new ArrayList<Double>();
				
				lastDate = d;
				priceForThisInterval.add(price);
			}
			Double btcCount = Double.parseDouble(s[2]);
			
			//days.add(new Day(d, price));
		}
		
		//dnew.addAll(days.subList(size-1000, size-1));
		stock.setDays(days);
		
		return stock;
	}
	
	
	public static Stock loadBTCDataNew(){
		
		Stock stock = new Stock();
		
		List<Day> days = new ArrayList<Day>();
		
		
		for(Order o : Order.loadOrdersCompleted()){
			
			days.add(new Day(o.getDate(), o.getPrice()));
		}
		
		stock.setDays(days);
		
		return stock;
	}
	
	
	
	
	
	
	static Stack<String> stack = new Stack<String>();
	
	
	/**
	 * Read in the data from yahoo and store it in the stack.
	 * @param yahooUrl
	 * @return Number of read rows
	 */
	private static int fillStackWithYahooData(URL yahooUrl) {
		int i=0;
		BufferedReader in = null;
		try{
			in = new BufferedReader(new InputStreamReader(yahooUrl.openStream()));
			String inputLine;
	
			
	
			while ((inputLine = in.readLine()) != null) {
				if(i!=0){
	
					stack.push(inputLine);
	
				}
				i++;
			}
	
			if(i<2){
				//logger.error("Nothing was in the yahoo file");
				return 0;
			}
		}catch(Exception e){
			//logger.error("Error while reading data from yahoo", e);
		}finally{
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return i;
	}
	
	
	public static double getAverage(List<Double> list){
		
		Double result = 0d;
		
		for(Double d : list){
			result += d;
		}
		
		return result/(list.size());
	}
}
